#include <irrlicht.h>
#include "bullet.h"
#include "world.h"

using namespace irr;
using namespace core;
using namespace video;

Bullet::Bullet(World* _world, position2df _pos, f32 _angle, u32 _id)
{
	world = _world;
	id = _id;
	pos   = _pos;
	angle = _angle;

	startPos = pos + vector2df(30, 0).rotateBy(-angle);

	bulletImage = world->driver->getTexture("./Data/Textures/bullet.png");
	if (bulletImage == NULL) throw L"Can't load bullet.png";
}

void Bullet::BulletFlying()
{
	//move bullet
	pos += vector2df(BULLET_SPEED, 0).rotateBy(-angle);
	recti worldRect = world->GetWorldSize();
	if (!worldRect.isPointInside(position2di(pos.X, pos.Y)))
	{
		world->RemoveBullet(id);
	}
}

void Bullet::Draw()
{
	u32 bulletWidth  = bulletImage->getSize().Width;
	u32 bulletHeight = bulletImage->getSize().Height;
	world->draw2DImage(bulletImage, recti(vector2di(0, 0), bulletImage->getSize()), 
		position2di(pos.X-bulletWidth/2, pos.Y-bulletHeight/2), 
		position2di(pos.X, pos.Y), angle, vector2df(1, 1), true, SColor(255, 255, 255, 255));
	
	//draw TRACE
	const u32 TRACE_LENGTH = 200;
	vector2df lineStartF = pos + vector2df(bulletWidth/2,0).rotateBy(-angle-180);//near bullet
	vector2df lineEndF = startPos;
	if ((pos-startPos).getLength() >= TRACE_LENGTH)
		lineEndF.set( pos + vector2df(bulletWidth/2+TRACE_LENGTH, 0).rotateBy(-angle-180) );
	vector2di lineStart(lineStartF.X, lineStartF.Y);
	vector2di lineEnd(lineEndF.X, lineEndF.Y);
	SColor color(100, 150, 150, 250);
	lineStart += vector2di(2, 0).rotateBy(90);
	lineEnd   += vector2di(2, 0).rotateBy(90);
	world->driver->draw2DLine(vector2di(lineStart.X, lineStart.Y), 
							  vector2di(lineEnd.X, lineEnd.Y), color);
	lineStart += vector2di(bulletHeight/2+1, 0).rotateBy(-90);
	lineEnd   += vector2di(bulletHeight/2+1, 0).rotateBy(-90);
	world->driver->draw2DLine(vector2di(lineStart.X, lineStart.Y), 
							  vector2di(lineEnd.X, lineEnd.Y), color);
}

u32 Bullet::getId()
{
	return id;
}